<template>
  <div class="edit">

    <Head :title="title"></Head>
    <van-address-edit :area-list="areaList" show-set-default show-search-result
      :area-columns-placeholder="['请选择', '请选择', '请选择']" @save="onSave" :address-info="AddressInfo" />
  </div>
</template>

<script setup>
import { useRoute, useRouter } from 'vue-router'

import { ref } from 'vue'
import Head from '@/components/title.vue'
import { areaList } from '@vant/area-data'
import { saveAction, detailAction } from '@/api/mine'
import { showToast } from 'vant'
const router = useRouter()
const route = useRoute()
console.log(route)
const title = ref('编辑地址')
const AddressInfo = ref({})
// 初始化地址
if (route.query.id) {
  title.value = '编辑地址'
  detailAction({
    id: route.query.id
  }).then((res) => {
    console.log(res)
    AddressInfo.value = {
      name: res.data.name,
      tel: res.data.mobile,
      city: res.data.address,
      addressDetail: res.data.address_detail,
      isDefault: !!res.data.is_default
    }
  })
} else {
  title.value = '新增地址'
}

// 点击保存的回调函数
const onSave = (res) => {
  if (route.query.id) {
    saveAction({
      address: res.city.value,
      addressId: route.query.id,
      checked: res.isDefault,
      detailadress: res.addressDetail,
      openId: localStorage.getItem('openId'),
      telNumber: res.tel,
      userName: res.name
    }).then((res) => {
      console.log(res)
      setTimeout(() => {
        router.push({ name: 'addressView' })
        showToast('保存成功')
      }, 1000)
    })
  } else {
    saveAction({
      address: res.city.value,
      addressId: '',
      checked: res.isDefault,
      detailadress: res.addressDetail,
      openId: localStorage.getItem('openId'),
      telNumber: res.tel,
      userName: res.name
    }).then((res) => {
      console.log(res)
      setTimeout(() => {
        router.push({ name: 'addressView' })
        showToast('保存成功')
      }, 1000)
    })
  }
}
</script>
<script>
export default {
  name: 'editView'
}
</script>

<style lang="scss" scoped>
</style>
